package com.kky.pp.adapter

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.kky.pp.R
import com.kky.pp.bean.AvatarBean
import com.custom.base.util.SDViewUtil
import com.kky.pp.util.GlideUtil
import com.youth.banner.adapter.BannerAdapter

class PageLoaderAdapter(
    val mActivity: Activity,
    val data: List<AvatarBean>,
    val position: Int = 0
) : BannerAdapter<AvatarBean, PageLoaderAdapter.BannerViewHolder>(data) {
    //创建ViewHolder，可以用viewType这个字段来区分不同的ViewHolder
    override fun onCreateHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
        val view = SDViewUtil.getRId(parent.context, R.layout.item_start_page)
        //注意，必须设置为match_parent，这个是viewpager2强制要求的
        view.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        return BannerViewHolder(view)
    }

    override fun onBindView(holder: BannerViewHolder?, bean: AvatarBean, position: Int, size: Int) {
        holder?.apply {
            val iv = view.findViewById<ImageView>(R.id.imgViewItemStartPage)

            Glide.with(iv)
                .load(bean.imageUrl)
                .placeholder(R.mipmap.icon_image_loading)
                .error(R.drawable.image_error)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()
                .into(iv)

            if (position == 0 && position + 1 < data.size){
                //如果是第一张 缓存加载第二张图片
                val avatar = data[position + 1]
                GlideUtil.preloadImage(mActivity,image = avatar.imageUrl)
            }
        }
    }

    inner class BannerViewHolder(var view: View) : RecyclerView.ViewHolder(
        view
    )
}